import seaborn as sns
import os
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

# 创建输出文件夹
os.makedirs('plot_output', exist_ok=True)

# 设置中文字体（根据您的系统选择）
try:
    plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # Windows
    plt.rcParams['axes.unicode_minus'] = False
except:
    try:
        plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']  # Mac
    except:
        pass  # 如果都没有，可能需要安装字体


# 热力图保存函数
def save_heatmap():
    import seaborn as sns
    import numpy as np

    hours = list(range(24))
    days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    data = np.random.rand(len(days), len(hours)) * 1000
    plt.figure(figsize=(12, 6))
    sns.heatmap(data, xticklabels=hours, yticklabels=days, cmap="YlGnBu")
    plt.title("24小时用户活跃时段分布热力图")
    plt.xlabel("小时")
    plt.ylabel("星期")
    plt.savefig('plot_output/heatmap.png', bbox_inches='tight', dpi=300)
    plt.close()


# 热力图保存函数
def save_heatmap():
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt

    # 读取数据
    data = pd.read_csv('ana_out/user_activity_heatmap_data.csv')

    # 设置"Day"列为索引
    data.set_index('Day', inplace=True)

    # 转置数据，使天数为行，小时为列
    data = data.transpose()

    # 定义正确的顺序
    days_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    hours_order = ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00',
                   '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00',
                   '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00']

    # 重新索引以保持正确的顺序
    data = data.reindex(days_order)
    data = data[hours_order]

    # 创建热力图
    plt.figure(figsize=(16, 8))
    sns.heatmap(data, cmap='YlOrRd', annot=True, fmt='d', linewidths=.5,
                annot_kws={"size": 8}, cbar_kws={'label': 'User Activity'})

    # 设置图表标题和标签
    plt.title('User Activity Heatmap by Day and Hour', pad=20, fontsize=16)
    plt.xlabel('Hour of Day', fontsize=12)
    plt.ylabel('Day of Week', fontsize=12)
    plt.xticks(rotation=45)
    plt.yticks(rotation=0)

    # 调整布局
    plt.tight_layout()
    plt.savefig('plot_output/user_activity_heatmap.png', dpi=300, bbox_inches='tight')

    # 显示图表
    plt.show()


# 折线图保存函数
def save_linechart():
    import os
    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib import rcParams

    # 1. 设置中文字体和输出目录
    rcParams['font.sans-serif'] = ['Microsoft YaHei']  # Windows系统使用微软雅黑
    rcParams['axes.unicode_minus'] = False  # 解决负号显示问题
    os.makedirs('plot_output', exist_ok=True)  # 创建输出目录

    # 2. 从文件读取数据（假设文件格式为CSV，包含province和total_sales列）
    try:
        df = pd.read_csv('ana_out/sales_region_dist.csv')

        # 3. 获取销售额前十的省份
        top10_provinces = df.sort_values('total_sales', ascending=False).head(10)['province'].tolist()

        # 4. 创建模拟的月度数据（实际应用中应从您的数据源获取真实月度数据）
        months = ['1月', '2月', '3月', '4月', '5月', '6月']
        monthly_data = []

        # 为每个省份生成模拟的月度增长数据
        for province in top10_provinces:
            base_sales = df[df['province'] == province]['total_sales'].values[0]
            monthly_sales = [int(base_sales * (0.9 + 0.02 * i)) for i in range(len(months))]
            monthly_data.append(monthly_sales)

        # 5. 创建DataFrame
        trend_data = pd.DataFrame(monthly_data, index=top10_provinces, columns=months).T

        # 6. 绘制折线图
        plt.figure(figsize=(12, 6))

        # 为每个省份绘制折线
        for province in top10_provinces:
            plt.plot(trend_data.index, trend_data[province], marker='o', linewidth=2, markersize=8, label=province)

        # 设置图表样式
        plt.title('销售额前十省份月度趋势对比', fontsize=16, pad=20)
        plt.xlabel('月份', fontsize=12, labelpad=10)
        plt.ylabel('销售额 (元)', fontsize=12, labelpad=10)
        plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', frameon=False)
        plt.grid(True, linestyle='--', alpha=0.6)

        # 调整布局并保存
        plt.tight_layout()
        output_path = os.path.join('plot_output', 'top10_provinces_sales_trend.png')
        plt.savefig(output_path, dpi=300, bbox_inches='tight')
        plt.close()

        print(f"图表已成功保存到: {output_path}")

    except FileNotFoundError:
        print("错误: 未找到 sales_region_dist.csv 文件")
    except Exception as e:
        print(f"发生错误: {str(e)}")


# 词云保存函数
def save_wordcloud():
    from wordcloud import WordCloud
    from collections import Counter

    titles = " ".join([
        "抽纸,纸巾,家庭,实惠,家用,餐巾纸,面巾纸,卫生纸",
        "美白,牙膏,去黄,口臭,清新,口气,成人,正品",
        "洗车,毛巾,车用,吸水,擦车布,不伤车,抹布"
    ])

    words = titles.split(',')
    word_counts = Counter(words)

    wc = WordCloud(
        width=800,
        height=400,
        background_color='white',
        font_path='msyh.ttc'  # 指定中文字体文件
    ).generate_from_frequencies(word_counts)

    plt.figure(figsize=(12, 6))
    plt.imshow(wc, interpolation='bilinear')
    plt.axis("off")
    plt.title("商品评论高频关键词词云")
    plt.savefig('plot_output/wordcloud.png', bbox_inches='tight', dpi=300)
    plt.close()


# 地图保存函数
# 地图保存函数
def save_map():
    import plotly.express as px
    import pandas as pd

    df_map = pd.DataFrame({
        '省份': ['广东', '浙江', '福建', '湖北', '江西', '江苏', '山东', '河北'],
        '销售额': [173710, 164206, 37434, 14872, 13743, 9844, 7565, 4850]
    })

    fig = px.choropleth(
        df_map,
        locations='省份',
        locationmode='country names',  # 修改为正确的参数值
        color='销售额',
        scope='asia',
        color_continuous_scale='Blues',
        title='中国各省份销售密度分布'
    )
    fig.update_geos(fitbounds="locations")
    fig.write_html('plot_output/map.html')  # 保存为交互式HTML

if __name__ == "__main__":
    save_heatmap()
    save_linechart()
    save_wordcloud()
    save_map()
    print("所有图表已保存到 plot_output 文件夹")